package com.yx.frame.authority;

import java.security.MessageDigest;
import com.yx.frame.util.binary.Base64Utils;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public final class EncryptTools {

	public static String MD5(String str) throws Exception {
		String encode = str;
		StringBuilder stringbuilder = new StringBuilder();
		MessageDigest md5 = MessageDigest.getInstance("MD5");
		md5.update(encode.getBytes("utf-8"));
		byte[] str_encoded = md5.digest();
		for (int i = 0; i < str_encoded.length; i++) {
			if ((str_encoded[i] & 0xff) < 0x10) {
				stringbuilder.append("0");
			}
			stringbuilder.append(Long.toString(str_encoded[i] & 0xff, 16));
		}
		return stringbuilder.toString();
	}
	public static String AESEncrypt(String sSrc, String sKey) throws Exception {
		if (sKey == null)return null;
		if (sKey.length() != 16) return null;
		byte[] raw = sKey.getBytes();
		SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
		Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");		
		IvParameterSpec iv = new IvParameterSpec(sKey.getBytes());
		cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
		byte[] encrypted = cipher.doFinal(sSrc.getBytes());
		return Base64Utils.encode(encrypted);
	}
	public static String AESDecrypt(String sSrc, String sKey) throws Exception {
		try {			
			if (sKey == null)return null;
			if (sKey.length() != 16)return null;
			byte[] raw = sKey.getBytes("ASCII");
			SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
			Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
			IvParameterSpec iv = new IvParameterSpec(sKey.getBytes());
			cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
			//byte[] encrypted1 = Base64.decodeBase64(sSrc);
			byte[] encrypted1 = Base64Utils.decode(sSrc);
			try {
				byte[] original = cipher.doFinal(encrypted1);
				String originalString = new String(original);
				return originalString;
			} catch (Exception e) {
				return null;
			}
		} catch (Exception ex) {
			System.out.println(ex.toString());
			return null;
		}
	}

	public static void main(String[] args) {
		long t = System.currentTimeMillis();
		try {
			System.out.println(System.getProperty("java.version"));
		} catch (Exception e) {
			e.printStackTrace();
		}
		System.out.println("耗时：" + (System.currentTimeMillis() - t));
	}
}
